package ink.metoo.auto.fishpi.chatroom.handler

import com.google.gson.Gson
import com.google.gson.JsonObject
import ink.metoo.auto.fishpi.chatroom.ChatRooms
import ink.metoo.auto.fishpi.chatroom.Message
import ink.metoo.auto.fishpi.chatroom.RedPacket
import ink.metoo.auto.fishpi.chatroom.command.CommandFactory
import ink.metoo.auto.fishpi.chatroom.handler.redpacket.RedPacketHandlerFactory
import org.jline.jansi.Ansi

class MessageTypeHandler : TypeHandler {

    override val type: Message.Type = Message.Type.MSG

    override fun handle(text: String, message: Message) = analysisMessage(message, false)

    companion object {

        private val gson = Gson()

        fun analysisMessage(message: Message, history: Boolean) {
            val content = message.content ?: return

            if (message.isJsonContent) {
                val contentJson = gson.fromJson(content, JsonObject::class.java)

                when (contentJson.get("msgType").asString) {
                    // 红包
                    "redPacket" -> {
                        RedPacketHandlerFactory.handle(message, gson.fromJson(contentJson, RedPacket::class.java))
                    }
                    // 天气
                    "weather",
                    // 音乐
                    "music" -> {
                        ChatRooms.console(message, "${contentJson.get("msgType")} $contentJson")
                    }
                    else -> {
                        ChatRooms.console(message, contentJson.toString())
                    }
                }

            } else {
                ChatRooms.console(message, message.content.toShellText())
                if (!history) CommandFactory.handle(message)
            }
        }


        fun String?.toShellText(): String {
            if (this == null) {
                return ""
            }
            val regexATagValue = """@<a\b[^>]*>(.*?)</a>""".toRegex()
            return replace(regexATagValue, Ansi().bgRed().a("@$1").reset().toString())
                .replace("<p>|</p>".toRegex(), "")
                .replace("<strong>", Ansi().bold().toString())
                .replace("</strong>", Ansi().boldOff().toString())
                .replace("</?br\\s*/?>".toRegex(RegexOption.IGNORE_CASE), "\n")
        }

    }



}